package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.ArticleMapper;
import com.itheima.pojo.Article;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.Result;
import com.itheima.service.ArticleService;
import com.itheima.utils.ThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Override
    public Result<String> add(Article article) {
        article.setUpdateTime(LocalDateTime.now());
        article.setCreateTime(LocalDateTime.now());
        Integer userId = getUserId();
        article.setCreateUser(userId);
        this.save(article);
        return Result.success("添加文章成功");
    }

    @Override
    public Result<String> edit(Article article) {
        article.setUpdateTime(LocalDateTime.now());
        Integer userId = getUserId();
        article.setCreateUser(userId);
        this.updateById(article);
        return Result.success("添加文章成功");
    }

    @Override
    public PageBean<Article> getList(Integer pageNum, Integer pageSize, String title, String categoryId, String state) {
        PageBean<Article> pageBean = new PageBean<>();
        Integer userId = getUserId();

        PageHelper.startPage(pageNum, pageSize);

        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(title), Article::getTitle, title);
        queryWrapper.eq(StringUtils.isNotBlank(categoryId), Article::getCategoryId, categoryId);
        queryWrapper.eq(StringUtils.isNotBlank(state), Article::getState, state);
        queryWrapper.eq(userId!=null, Article::getCreateUser, userId);
        Page<Article> list = (Page<Article>) this.list(queryWrapper);
        pageBean.setTotal(list.getTotal());
        pageBean.setItems(list.getResult());
        return pageBean;
    }

    private Integer getUserId() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        return userId;
    }
}
